package com.ipay.core;

import java.io.IOException;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.ipay.exception.BaseException;
import com.ipay.utils.XmlUtils;

@Component
public class HttpGateway {
	private static Logger logger=LoggerFactory.getLogger(HttpGateway.class);
	public String url;
	public String key;
	public String notify_url;
	private static String localCharset = "UTF-8";
	private static String charset = "ISO-8859-1";
	public Param post(Param param) {
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		Param resultMap = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity entityParams = new StringEntity(XmlUtils.parseXML(param), localCharset);
            httpPost.setEntity(entityParams);
            httpPost.setHeader("Content-Type", "text/xml;charset=" + charset);
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            if(response != null && response.getEntity() != null){
            	resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), localCharset);
            }
        } catch (Exception e) {
        	logger.error("银行通讯失败", e);
            throw new BaseException("999999","银行通讯失败！");
        } finally {
            if(response != null){
                try {
					response.close();
				} catch (IOException e) {
					logger.error("关闭返回信息失败", e);
				}
            }
            if(client != null){
                try {
					client.close();
				} catch (IOException e) {
					logger.error("通讯资源关闭失败", e);
				}
            }
        }
		return resultMap;
	}
}
